using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Collections.Generic;
using System.Linq;

namespace P3.Modules.SharePoint.SPExplorerS.Features.SPExplorerS
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("595d0c24-8318-426f-b675-43056057f1e0")]
    public class SPExplorerSEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        private string[] folderUrls = { "Style Library", "SitePages" };

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = (properties.Feature.Parent as SPSite).RootWeb;
                SPFolderCollection folders = web.RootFolder.SubFolders;

                foreach (string folderUrl in folderUrls)
                {
                    try
                    {
                        SPFolder folder = GetFolderByUrl(folders, folderUrl);
                        if (folder != null)
                        {
                            SPFileCollection p3files = GetFilesFromFolder(folder.SubFolders, "P3");
                            PublishFiles(p3files);
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        private void PublishFiles(SPFileCollection p3files)
        {
            if (p3files == null)
            {
                return;
            }

            foreach (SPFile f in p3files)
            {
                CheckinFile(f);
            }
        }

        private static void CheckinFile(SPFile f)
        {
            try
            {
                if (f.Level.ToString().Equals("Checkout"))
                {
                    f.CheckIn(String.Empty, SPCheckinType.MajorCheckIn);
                }
            }
            catch (Exception)
            {
                
            }
        }

        private SPFileCollection GetFilesFromFolder(SPFolderCollection folders, string subFolderName)
        {
            try
            {
                SPFolder p3folder = folders[subFolderName];

                return p3folder.Files;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static SPFolder GetFolderByUrl(SPFolderCollection folders, string folderUrl)
        {
            try
            {
                return folders[folderUrl];
            }
            catch (Exception)
            {
                return null;
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb web = (properties.Feature.Parent as SPSite).RootWeb;
                SPFolderCollection folders = web.RootFolder.SubFolders;

                foreach (string folderUrl in folderUrls)
                {
                    try
                    {

                        SPFolder folder = GetFolderByUrl(folders, folderUrl);
                        if (folder != null)
                        {
                            SPFolder p3Folder = GetFolderByUrl(folder.SubFolders, "P3");
                            if (p3Folder != null)
                            {
                                p3Folder.Delete();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                DeleteWebPart(web.GetCatalog(SPListTemplateType.WebPartCatalog));
                DeleteXaP(web.GetCatalog(SPListTemplateType.MasterPageCatalog));
            }
            catch (Exception)
            {

            }
        }

        private void DeleteXaP(SPList sPList)
        {
            SPFolder xapFolder = GetFolderByUrl(sPList.Folders, "_catalogs/masterpage/ClientBin/P3.Modules.SharePoint.SPExplorerS");

            if (xapFolder!=null)
            {
                xapFolder.Delete();
            }
        }

        private static SPFolder GetFolderByUrl(SPListItemCollection folders, string folderUrl)
        {
            if (folders == null)
            {
                return null;
            }

            if (String.IsNullOrEmpty(folderUrl))
            {
                return null;
            }

            SPFolder folder = null;

            SPListItem item = (from SPListItem i
                               in folders
                               where i.Url.Equals(folderUrl, StringComparison.InvariantCultureIgnoreCase)
                               select i).FirstOrDefault();

            if (item != null)
            {
                folder = item.Folder;
            }

            return folder;
        }

        private void DeleteWebPart(SPList sPList)
        {
            SPListItemCollection webPartColl = sPList.Items;

            try
            {
                SPItem WPToDel = null;

                foreach (SPListItem item in webPartColl)
                {
                    if (item.Name.Equals("P3.Tools.SPExplorerWebPart.webpart"))
                    {
                        WPToDel = item;
                        break;
                    }
                }

                if (WPToDel != null)
                {
                    WPToDel.Delete();
                }

            }
            catch (Exception)
            {

            }
        }



        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
